<template>

	<view class="bg-[var(--page-bg-color)] min-h-[100vh] overflow-hidden member-edit" :style="themeColor()">
		<u-form labelPosition="top" :model="formData" errorType='toast' :rules="rules" ref="formRef">
			<view class="sidebar-margin card-template mt-[var(--top-m)]  mb-[var(--top-m)] py-[20rpx]">
				<!-- <view class="mt-[32rpx]">
					<view class="flex w-full justify-center relative">
						<view>
							<u-upload @afterRead="afterRead" :maxCount="1" width="100" height="100">
								<u-avatar :src="img(formData.avatar)" v-if="formData.sex == 1"
									:default-url="img(formData.sex == 1 ? 'https://files.meton.vip/2505b83651e015d924ace57b74a918b4b499dac599abd70578d759552e819f85.jpeg' : 'https://files.meton.vip/135c0de56684ed648a9d869eab04fc1101344cc24b34a2e3ac69159465a3323b.png')"
									size="100" />
								<u-avatar :src="img(formData.avatar)" v-if="formData.sex == 2"
									:default-url="img(formData.sex == 1 ? 'https://files.meton.vip/2505b83651e015d924ace57b74a918b4b499dac599abd70578d759552e819f85.jpeg' : 'https://files.meton.vip/135c0de56684ed648a9d869eab04fc1101344cc24b34a2e3ac69159465a3323b.png')"
									size="100" />
							</u-upload>
						</view>

					</view>
				</view> -->
				<view class="mt-[16rpx]">
					<u-form-item :label="'是否匿名会员'" prop="anonymous" labelWidth="250rpx">
						<u-subsection :list="anonymousList" @change="updateAnonymous" mode="button" :fontSize="16"
							activeColor="var(--primary-color)" :current="anonymousIndex"></u-subsection>

					</u-form-item>
				</view>
				<!-- 会员姓名 -->
				<view class="mt-[16rpx]" v-if="formData.anonymous == 1">
					<u-form-item :label="t('name')" prop="name" labelWidth="200rpx" required>
						<u-input fontSize="32rpx" v-model.trim="formData.name" class="h-[52rpx]  py-[8rpx] px-[18rpx]" clearable maxlength="25"
							placeholderStyle="color: #888" :placeholder="t('namePlaceholder')">
						</u-input>
					</u-form-item>
				</view>
				<!-- 会员昵称 -->
				<view class="mt-[16rpx]" v-if="formData.anonymous == 0">
					<u-form-item :label="t('nickName')" prop="nickname" labelWidth="200rpx">
						<u-input fontSize="32rpx" v-model.trim="formData.nickname" class="h-[52rpx]  py-[8rpx] px-[18rpx]" clearable maxlength="25"
							placeholderStyle="color: #888" :placeholder="t('nickNamePlaceholder')" />
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="'会员性别'" prop="sex" labelWidth="200rpx">
						<u-subsection :list="sexList" @change="updateSex" mode="button" activeColor="var(--primary-color)"
							:fontSize="16" :current="sexIndex"></u-subsection>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]" v-if="formData.anonymous == 1">
					<u-form-item :label="'手机号码'" prop="mobile" labelWidth="200rpx" required>
						<u-input fontSize="32rpx" v-model.trim="formData.mobile" class="h-[52rpx]  py-[8rpx] px-[18rpx]" maxlength="11" clearable
							:placeholder="t('mobilePlaceholder')" placeholderStyle="color: #888">
							<template #suffix> <sms-code :mobile="formData.mobile" type="login" class="text-[32rpx]"
									v-model="formData.mobile_key"></sms-code>
							</template>
						</u-input>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]" v-if="formData.anonymous == 0">
					<u-form-item :label="'手机号码'" labelWidth="200rpx">
						<u-input fontSize="32rpx" v-model.trim="formData.mobile" maxlength="11" clearable
							:placeholder="t('mobilePlaceholder')" placeholderStyle="color: #888">
							<template #suffix> <sms-code :mobile="formData.mobile" type="login"
									v-model="formData.mobile_key"></sms-code>
							</template>
						</u-input>
					</u-form-item>
				</view>

				<view class="mt-[16rpx]" v-if="formData.mobile_key">
					<u-form-item :label="'验证码'" prop="code" labelWidth="200rpx">
						<u-input fontSize="32rpx" v-model.trim="formData.code" maxlength="6" clearable :placeholder="'请输入验证码'"
							placeholderStyle="color: #888">
						</u-input>
					</u-form-item>
				</view>
				<template v-if="formData.id == undefined">
					<view class="mt-[16rpx]">
						<u-form-item :label="'消费密码'" prop="paypasswd" labelWidth="200rpx">
							<u-code-input v-model="formData.paypasswd" dot :maxlength="6" size="36"
								class="w-[100%] justify-between"></u-code-input>
						</u-form-item>
					</view>
				</template>
				<view class="mt-[16rpx]">
					<u-form-item :label="'是否农历'" prop="isLunar" labelWidth="200rpx">
						<u-subsection :list="lunarList" @change="updateLunar" mode="button" activeColor="var(--primary-color)"
							:fontSize="16" :current="lunarIndex"></u-subsection>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="'会员生日'" prop="birthday" labelWidth="200rpx">
						<view class="flex flex-1 u-border rounded-[8rpx]">
							<view class="flex   flex-1 items-center   h-[52rpx]  py-[12rpx] px-[18rpx]">
								<picker mode="selector" :value="yearId" :range="year" @change="changeYear" style="width: 33%">
									<view class="text-[#303133] text-[32rpx]" style="text-align: center;">{{ year[yearId] }} 年
									</view>
								</picker>
								<view>-</view>
								<picker mode="selector" :range="month" @change="changeMonth" style="width: 33%">
									<view class="text-[#303133] text-[32rpx] " style="text-align: center;">{{ month[monthId] }} 月
									</view>
								</picker>
								<view>-</view>
								<picker mode="selector" :range="day" @change="changeDay" style="width: 33%">
									<view class="text-[#303133] text-[32rpx]" style="text-align: center;">{{ day[dayId] }} 日</view>
								</picker>
							</view>
						</view>

					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item :label="'归属员工'" prop="employee" labelWidth="200rpx">
						<view class="flex flex-1 u-border rounded-[8rpx]">

							<view @click="employeeSheetShow()" v-if="formData.employee"
								class="flex h-[52rpx]  items-center  py-[10rpx] px-[18rpx]"
								:class="formData.employee ? ' text-[#303133]' : 'text-[gray]'">
								<view class="w-[50rpx] h-[50rpx] relative rounded-[8rpx]">
									<image
										:src="employeeInfo?.avatar || 'https://files.meton.vip/2310e2533cff85c0f22420d6b0950a372b769f45ed8a720cfbd9597a5fdd5c42.png'"
										class="w-[50rpx] h-[50rpx]"></image>

								</view>
								<view class="flex-1  flex items-center ml-[20rpx]   box-border py-[10rpx] border-0">
									<view class="flex-1">
										<view class="text-[32rpx] text-[#333]  truncate max-w-[260rpx]">{{
											employeeInfo?.employeeName }}
											<text class="text-[26rpx] ">（{{
												employeeInfo?.job }}）</text>
										</view>

									</view>
								</view>
							</view>
							<view v-else @click="employeeSheetShow()"
								class="flex w-full h-[52rpx]   items-center   py-[12rpx] px-[18rpx] text-size-[32rpx]"
								:class="formData.employee ? 'text-[#303133]' : 'text-[gray]'">
								{{ formData.employee ? formData.employee : '请选择归属员工' }}
							</view>
						</view>

					</u-form-item>
					<view class="mt-[16rpx]">
						<u-form-item :label="'推荐会员'" prop="spreadId" labelWidth="200rpx">
							<view class="flex flex-1 u-border rounded-[8rpx]">
								<view @click="memberSheetShow()" v-if="formData.spreadId"
									class="flex h-[52rpx]  items-center  py-[8rpx] px-[18rpx]"
									:class="formData.spreadId ? ' text-[#303133]' : 'text-[gray]'">
									<view class="w-[50rpx] h-[50rpx] relative rounded-[8rpx]">
										<image
											:src="spreadMemberInfo?.avatar || 'https://files.meton.vip/2310e2533cff85c0f22420d6b0950a372b769f45ed8a720cfbd9597a5fdd5c42.png'"
											class="w-[50rpx] h-[50rpx]"></image>

									</view>
									<view class="flex-1  flex items-center ml-[20rpx]   box-border py-[10rpx] border-0">
										<view class="flex-1">
											<view class="text-[32rpx] text-[#333]  truncate max-w-[260rpx]">{{
												spreadMemberInfo?.nickname }}

											</view>

										</view>
									</view>
								</view>
								<view v-else @click="memberSheetShow()"
									class="flex w-full h-[52rpx]   items-center   py-[12rpx] px-[18rpx] text-size-[32rpx]"
									:class="formData.spreadId ? 'text-[#303133]' : 'text-[gray]'">
									{{ formData.spreadId ? formData.spreadId : '请选择推荐会员' }}
								</view>
							</view>

						</u-form-item>
					</view>

					<view class="mt-[16rpx]">
						<u-form-item :label="'会员备注'" prop="mark" labelWidth="200rpx">
							<u-input fontSize="32rpx" class="h-[52rpx]  py-[8rpx] px-[18rpx]" type="text" v-model.trim="formData.mark" clearable :placeholder="'请输入会员备注'"
								placeholderStyle="color: #888">
							</u-input>

						</u-form-item>
					</view>

				</view>




				<!-- <view class="mt-[16rpx]">
					<u-form-item :label="'会员来源'" prop="mobile" labelWidth="200rpx">

						<view class="flex flex-1 u-border rounded-[8rpx]">
							<view @click="sourceSheetShow()" class="flex w-full  h-[52rpx]   items-center   py-[12rpx] px-[18rpx]"
								:class="formData.sourceName ? ' text-[#303133]' : 'text-[gray]'">
								{{ formData.sourceName ? formData.sourceName : '请选择会员来源' }}
							</view>
						</view>
					</u-form-item>
				</view> -->
			</view>

		</u-form>
		<view class="w-full footer">
			<view
				class="py-[var(--top-m)] px-[var(--sidebar-m)] footer  w-full fixed bottom-0 left-0 right-0 box-border z-999"
				style="background-color: #fff;">
				<button hover-class="none"
					class="primary-btn-bg !text-[#fff] h-[100rpx] leading-[100rpx] rounded-[50rpx] text-[36rpx] font-500"
					@click="save" :disabled="btnDisabled" :loading="operateLoading" :class="{ 'opacity-50': btnDisabled }">{{
						t('save') }}</button>
			</view>
		</view>
		<!-- 选择归属员工 -->
		<select-employeeBelong ref="employeeRef" :is-radio="true" @confirm="updateEmployee" />
		<!-- 选择推荐会员 -->
		<select-memberBelong ref="memberRef" :is-radio="true" @confirm="updateMember" />

		<!-- #ifdef MP-WEIXIN -->
		<!-- 小程序隐私协议 -->
		<wx-privacy-popup ref="wxPrivacyPopupRef"></wx-privacy-popup>

		<!-- #endif -->
	</view>
	<!-- 水印 -->
	<watermark></watermark>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { img, redirect } from '@/utils/common'
import { t } from '@/locale'
import { createUser, updateUser, getUser } from '@/app/api/shopMember';

import { uploadImage } from '@/app/api/system'

const formData: any = ref({
	id: undefined,
	avatar: '',
	anonymous: 1,
	name: '',
	nickname: '',
	mobile: undefined,
	code: undefined,
	employee: '',
	employeeId: '',
	password: undefined,
	paypasswd: undefined,
	checkPassword: undefined,
	year: undefined,
	month: undefined,
	day: undefined,
	sex: 2,
	isLunar: false,
	source: undefined,
	mark: undefined,
	spreadId: undefined,
	spreadName: undefined,

})
const formRef: any = ref(null)
const btnDisabled = ref(false)


const wxPrivacyPopupRef: any = ref(null)
/**
 * 实名 匿名会员
 */
const anonymousList = computed(() => {
	return [
		{ name: '实名会员', value: 1 },
		{ name: '匿名会员', value: 0 },
	]
})
const anonymousIndex = ref(0)
const updateAnonymous = (index: number) => {
	anonymousIndex.value = index
	formData.value.name = ''
	formData.value.nickname = ''
	formData.value.anonymous = anonymousList.value[index].value
}
/**
 * 是否 农历生日
 */
const lunarList = computed(() => {
	return [
		{ name: '公历生日', value: false },
		{ name: '农历生日', value: true },
	]
})
const lunarIndex = ref(0)
const updateLunar = (index: number) => {
	lunarIndex.value = index
	formData.value.isLunar = lunarList.value[index].value
}
// 获取年月日
const year: any = ref([])
const yearId = ref('')
const month: any = ref([])
const monthId = ref('')
const day: any = ref([])
const dayId = ref('')

const getDate = () => {
	let currentYear = new Date().getFullYear()
	for (let i = currentYear - 60; i < currentYear + 100; i++) {
		year.value.push(i)
	}
	for (let i = 0; i < 12; i++) {
		month.value.push(i + 1)
	}


}
const changeYear = (e: any) => {
	console.log(e)

	yearId.value = e.detail.value
	formData.value.year = year.value[e.detail.value]
}
const changeMonth = (e: any) => {
	console.log(e)
	monthId.value = e.detail.value
	formData.value.month = month.value[e.detail.value]
	let for_month = 0
	if (month.value[e.detail.value] == 2) {
		for_month = 29
	} else if ([1, 3, 5, 7, 8, 10, 12].indexOf(month.value[e.detail.value]) != -1) {
		for_month = 31
	} else {
		for_month = 30
	}
	for (let i = 0; i < for_month; i++) {
		day.value.push(i + 1)
	}

}
const changeDay = (e: any) => {
	dayId.value = e.detail.value
	formData.value.day = day.value[e.detail.value]

}

onLoad(async (data: any) => {
	getDate()

	if (data.id) {
		const { data: memberInfo } = await getUser(data.id)
		formData.value = memberInfo
		if (formData.value.employee) {
			employeeInfo.value = formData.value.employeeInfo
		}
		if (formData.value.spreadId) {
			const { data: spreadInfo } = await getUser(formData.value.spreadId)
			spreadMemberInfo.value = spreadInfo
			console.log(spreadMemberInfo.value)
		}
		anonymousIndex.value = anonymousList.value.findIndex((item: any) => item.value == memberInfo.anonymous)
		sexIndex.value = sexList.value.findIndex((item: any) => item.value == memberInfo.sex)
		lunarIndex.value = lunarList.value.findIndex((item: any) => item.value == memberInfo.isLunar)
		yearId.value = year.value.findIndex((item: any) => item == memberInfo.year)
		monthId.value = month.value.findIndex((item: any) => item == memberInfo.month)
		changeMonth({
			detail: {
				value: monthId.value
			}
		})
		dayId.value = day.value.findIndex((item: any) => item == memberInfo.day)

	} else {
		formData.value.anonymous = 1
		formData.value.sex = 2
		formData.value.isLunar = false
	}

	// #ifdef MP
	nextTick(() => {
		if (wxPrivacyPopupRef.value) wxPrivacyPopupRef.value.proactive();
	})
	// #endif
})


const rules = computed(() => {
	if (formData.value.anonymous == 1) {
		return {
			'name': {
				type: 'string',
				required: true,
				message: t('namePlaceholder'),
				trigger: ['blur', 'change'],
			},
			'employee': {
				type: 'string',
				required: true,
				message: '请选择归属员工',
				trigger: ['blur', 'change'],
			},
			'mobile': [
				{
					type: 'string',
					required: true,
					message: t('mobilePlaceholder'),
					trigger: ['blur', 'change'],
				},
				{
					validator(rule: any, value: any, callback: any) {
						let mobile = /^1[3-9]\d{9}$/;
						if (!mobile.test(value)) {
							callback(new Error(t('mobileError')))
						} else {
							callback()
						}
					}
				}
			],

		}
	} else {
		return {

			'nickname': {
				type: 'string',
				required: true,
				message: '请输入会员昵称',
				trigger: ['blur', 'change'],
			},
			'employee': {
				type: 'string',
				required: true,
				message: '请选择归属员工',
				trigger: ['blur', 'change'],
			}


		}
	}

})





const operateLoading = ref(false)
const save = () => {
	formData.value.mobile = formData.value.mobile ? formData.value.mobile : undefined
	const save = formData.value.id ? updateUser : createUser
	formRef.value.validate().then(() => {
		if (operateLoading.value) return
		operateLoading.value = true
		btnDisabled.value = true
		console.log(formData.value)
		delete formData.value.birthday
		save(formData.value).then((res: any) => {
			operateLoading.value = false
			setTimeout(() => {
				btnDisabled.value = false

				redirect({
					url: '/app/pages/shopMember/member',
					mode: 'redirectTo',
					// param: { source: source.value }
				})
			}
				, 1000)
		}).catch(() => {
			operateLoading.value = false
			btnDisabled.value = false
		})
	})
}






/**
 * 选择头像
 */
const afterRead = (event: any) => {
	console.log(event)
	uploadImage({
		filePath: event.file.url,
		name: 'file'
	}).then((res: any) => {
		formData.value.avatar = res.data
	}).catch(() => {
	})
}
/**
 * 修改性别
 */
const sexList = computed(() => {
	return [
		{ name: '女', value: '2' },

		{ name: '男', value: '1' }
	]
})
const sexIndex = ref(0)
const updateSex = (index: any) => {
	sexIndex.value = index
	formData.value.sex = sexList.value[index].value
	console.log(formData.value.sex)

}
/**
 * 选择归属员工
 */
const employeeRef = ref()
const employeeSheetShow = () => {
	employeeRef.value.open([])
}
const employeeInfo = ref()
const updateEmployee = (e: any) => {
	formData.value.employee = e[0].employeeName

	formData.value.employeeId = e[0].employeeId
	employeeInfo.value = e[0]
}
/**
 * 选择推荐会员
 */
const memberRef = ref()
const memberSheetShow = () => {
	memberRef.value.open([])
}
const spreadMemberInfo = ref()
const updateMember = (e: any) => {

	formData.value.spreadId = e[0].id
	formData.value.spreadName = e[0].nickname
	spreadMemberInfo.value = e[0]
}





/**
 *选择会员来源 
 */
const sourceRef = ref()

const sourceSheetShow =
	() => {
		sourceRef.value.open()
	}

const updateSource = (e: any) => {
	formData.value.source = e.province.id
	formData.value.sourceName = e.province.label


}
</script>

<style lang="scss" scoped>
:deep(.u-upload) {
	flex: none;
}

.member-edit :deep(.u-form-item__body__left__content__label) {
	font-size: 38rpx !important;
}

.member-edit :deep(.u-form-item__body__right) {
	display: flex;
}

:deep(.cell-group) {
	.u-cell {
		.u-cell__body {
			padding: 0;
		}
	}
}

:deep(.u-code-input) {
	justify-content: space-between;
}


.footer {
	height: calc(100rpx + var(--top-m) + var(--top-m) + constant(safe-area-inset-bottom)) !important;
	height: calc(100rpx + var(--top-m) + var(--top-m) + env(safe-area-inset-bottom)) !important;
}
</style>